<?php


declare(strict_types=1);

namespace app\operations\controller\admin;

use app\admin\model\auth\Admin as AdminModel;
use app\operations\model\Brand as BrandModel;
use app\operations\model\Organ as OrganModel;
use app\operations\model\Store as StoreModel;
use app\operations\service\Wallet as WalletService;

use sheep\controller\Backend;
use sheep\controller\traits\Crud;
use sheep\exception\SheepException;
use think\facade\Db;
use think\Request;
use think\Response;

//商家
class Shop extends Backend
{

    use Crud;
    protected $model = null;
    protected $organModel = null;
    protected $storeModel = null;

    protected function initialize()
    {
        $this->model = new AdminModel;
        $this->organModel = new OrganModel;
        $this->storeModel = new StoreModel;
    }


    /**
     * 查看
     *
     * @return Response
     */
    public function list(Request $request): Response
    {
        $params = $request->param();

        $search = json_decode($params['search'], true);
        $where = [];
        if(!empty($search['address'])){
            $name = $search['address'][0];
            $ids = $this->storeModel
                ->where('address', 'like', '%' . $name . '%')  // 使用like进行模糊查询
                ->column('organ_id');
            // 对 $ids 进行去重
            $ids = array_unique($ids);
            if(!empty($ids)){
                $where[1] = ['organ_id','in', implode(',', $ids)];
            }else{
                $where['id'] = ['=', '99999999'];
            }
        }


        if(!empty($search['store.name'])){
            $name = $search['store.name'][0];
            $ids = $this->storeModel
                ->where('name', 'like', '%' . $name . '%')  // 使用like进行模糊查询
                ->column('organ_id');
            // 对 $ids 进行去重
            $ids = array_unique($ids);
            if(!empty($ids)){
                $where[1] = ['organ_id','in', implode(',', $ids)];
            }else{
                $where['id'] = ['=', '99999999'];
            }
        }

        $data = $this->model->with(['organ','store'])
            ->where($where)
            ->sheepFilter(true, function ($filters) {
                unset($filters['store.name']);
                unset($filters['address']);
                return $filters;
            })
            ->where('status', 'normal')
            ->where('id','>=', 35)
            ->where('organ_id', '<>', '0')
            ->where('role_id', '=', '3')
            ->order('create_time', 'desc')
            ->order('id', 'desc')
            ->paginate($request->param('list_rows', 10));


        if(!empty($data)){
            foreach($data as &$val){
                $val['money'] = $val['organ']['money'] ?? 0.00;
                foreach($val['store'] as &$v){
                    $v['industry_name'] = '宠物行业';
                    $v['gmv'] = '0';
                }
            }
        }

        return success('获取成功', $data);
    }


    //新增账号
    public function add(Request $request)
    {
        $params = $this->request->only([
            'account',
            'mobile',
            'password',
            'avatar',
            'email',
            'status',
            'legal_person_name',
            'legal_person_bank_account',
            'legal_id_type',
            'legal_person_id_card',
            'legal_person_phone',
            'legal_id_images',
            'platform_pay_password',
            'contact_name',
            'entity_type',
            'entity_name',
            'business_license',
            'shop_type',
            'phone',
        ]);



        $shop_type = $params['shop_type'];
        unset($params['shop_type']);

        // 使用 explode 函数将字符串拆分成数组
        $card = explode(',', $params['legal_id_images']);
        $params['protrait_card'] = $card[0];
        $params['reverse_card'] = isset($card[1]) ? $card[1] : '';

        $this->svalidate($params, ".add");


        unset($params['protrait_card']);
        unset($params['reverse_card']);

        $data = Db::transaction(function () use ($params,$shop_type) {

            $organ = $this->organModel->create(['name'=>time().mt_rand(100000,999999)]);

            //创建admin商家账号
            $salt = mt_rand(1000, 9999);
            $params['role_id'] = 3;
            $params['password'] =md5(md5($params['password']) . $salt);
            $params['salt'] = $salt;
            $params['organ_id'] = $organ->id;

            $this->model->save($params);

            //分割分类数组
            $shop_type = explode(',',$shop_type);

            foreach($shop_type as $val){

                $shopData = [
                    'name' => '', // 店铺名称
                    'type' => $val, // 店铺类型，本地生活是团购,电商就是电商
                    'per_pay' => '0', // 人均消费
                    'level' => 'bronze', // 店铺等级
                    'thumb' => '', // 缩略图
                    'images' => '', // 店铺封面轮播图
                    'service' => '', // 服务标签
                    'business_status' => 'close', // 营业状态
                    'status' => 'normal', // 店铺状态
                    'business_rule' => '', // 营业规则
                    'mobile' => $params['mobile'], // 联系方式
                    'details' => '', // 详情
                    'category_tag' => '', // 标签
                    'brand_id' => null, // 品牌ID，没有就填0
                    'mark' => '5', // 店铺评分
                    'other_mark' => '5', // 其他评分
                    'organ_id' => $organ->id, // 组织ID
                    'security_deposit' => '5000.00', // 保障金金额
                    'is_deposit_paid' => 0, // 是否已缴纳保证金
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];

                Db::name('shop_store')->insert($shopData);

            }

        });

        return success('保存成功', $data);
    }



    /**
     * 编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        $params = $this->request->only([
            'account',
            'mobile',
            'password',
            'avatar',
            'email',
            'status',
            'legal_person_name',
            'legal_person_bank_account',
            'legal_id_type',
            'legal_person_id_card',
            'legal_person_phone',
            'legal_id_images',
            'platform_pay_password',
            'contact_name',
            'entity_type',
            'entity_name',
            'business_license',
            'phone',
            'shop_type',
        ]);
        $params['id']  = $id;


        // 使用 explode 函数将字符串拆分成数组
        $card = explode(',', $params['legal_id_images']);
        $params['protrait_card'] = $card[0];
        $params['reverse_card'] = isset($card[1]) ? $card[1] : '';

        $this->svalidate($params);

        unset($params['protrait_card']);
        unset($params['reverse_card']);


        $id = intval($id);

        $shop_type = $params['shop_type'];
        unset($params['shop_type']);

        Db::transaction(function () use ($id, $params,$shop_type) {

            $data = $this->model->where('id',$id)->find();

            if(!empty($params['password'])){
                //创建admin商家账号
                $salt = mt_rand(1000, 9999);
                $params['password'] =md5(md5($params['password']) . $salt);
                $params['salt'] = $salt;
            }

            $data->save($params);

            if(!empty($shop_type)) {

                //分割分类数组
                $shop_type = explode(',', $shop_type);

                $this->storeModel->where('organ_id', $data->organ_id)->whereNotIn('type', $shop_type)->update(['status' => 'close']);
                $this->storeModel->where('organ_id', $data->organ_id)->whereIn('type', $shop_type)->update(['status' => 'normal']);

                foreach ($shop_type as $val) {

                    $shopCount = $this->storeModel->where('organ_id', $data->organ_id)->where('type', $val)->count();

                    if ($shopCount == 0) {

                        $shopData = [
                            'name' => '', // 店铺名称
                            'type' => $val, // 店铺类型，本地生活是团购,电商就是电商
                            'per_pay' => '0', // 人均消费
                            'level' => 'bronze', // 店铺等级
                            'thumb' => '', // 缩略图
                            'images' => '', // 店铺封面轮播图
                            'service' => '', // 服务标签
                            'business_status' => 'close', // 营业状态
                            'status' => 'normal', // 店铺状态
                            'business_rule' => '', // 营业规则
                            'mobile' => $params['mobile'], // 联系方式
                            'details' => '', // 详情
                            'tag' => '', // 标签
                            'brand_id' => null, // 品牌ID，没有就填0
                            'mark' => '5', // 店铺评分
                            'other_mark' => '5', // 其他评分
                            'organ_id' => $data->organ_id, // 组织ID
                            'security_deposit' => '5000.00', // 保障金金额
                            'is_deposit_paid' => 0, // 是否已缴纳保证金
                            'create_time' => time(),
                            'update_time' => time(),
                        ];

                        Db::name('shop_store')->insert($shopData);

                    }
                }
            }else{
                $this->storeModel->where('organ_id', $data->organ_id)->update(['status' => 'close']);
            }

        });

        return success('更新成功');
    }



    /**
     * 账号详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {

        $data = $this->model->with(['store','organ'])->where('organ_id', '<>', '0')->findOrFail($id)->toArray();
        // 只获取 status 为 normal 的 store
        $filteredStores = array_filter($data['store'], function ($store) {
            return $store['status'] === 'normal';
        });

        $data['store_type'] = array_column($filteredStores, 'type');
        $data['referrer_name'] = '';  //邀请人
        $data['money'] = $data['organ']['money']; //余额
        $data['total_spent'] = 0;//共计消费

        return success('获取成功', $data);
    }


    public function recharge()
    {
        $params = $this->request->only(['id', 'type', 'amount', 'memo']);

        if (!in_array($params['type'], ['money', 'score'])) {
            throw new SheepException('参数错误');
        }

        $result = Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [], $params['memo']);
        });
        if ($result) {
            return success('充值成功');
        }
        return error('充值失败');
    }





}
